import axios from 'axios';
import router from '../router';
import { Message } from 'element-ui'

// 上传地址
export const UPLOAD_URL = 'https://aizhike.qiangfengkeji.com/ai_human/upload/uploadImage';
export const UPLOADV_URL = 'https://aizhike.qiangfengkeji.com/ai_human/upload/uploadVideo';
// export const UPLOAD_URL = 'http://192.168.0.108:8884/upload/uploadImage';
// export const UPLOADV_URL = 'http://192.168.0.108:8884/upload/uploadVideo';

axios.defaults.timeout = 300000; //请求超时30秒
axios.defaults.baseURL ='https://aizhike.qiangfengkeji.com/ai_human/';  //本地地址
// axios.defaults.baseURL ='http://192.168.0.108:8884/';  //本地地址
axios.defaults.headers.post['Content-Type'] = 'multipart/form-data'; //设置post请求是的header信息

//axios.defaults.withCredentials = true //要用到session验证码功能，让请求携带cookie

//http request 拦截器
axios.interceptors.request.use(
    config => {
      let token = sessionStorage.getItem('token')
      if (token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
        config.headers = {
          'X-token': token
        }
      }

      return config
    },
    err => {
      return Promise.reject(err)
    }
)

axios.interceptors.response.use(
    response => {
      // if (response.data.code === 200) {
      //   // localStorage.removeItem('token')
      //   router.push({
      //     path:"/login",
      //     querry:{redirect: router.currentRoute.fullPath}//从哪个页面跳转
      //   })
      // }
      return response
    },
    err => {
      if (err.code === 'ECONNABORTED' && err.message.indexOf('timeout') !== -1) {
        Message({
            message: '网络异常，连接超时...',
            type: 'warning'
        });
      }
      return Promise.reject(err)
    }
)

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url, params={}, headers={}){
    return new Promise((resolve, reject) => {
      axios.get(url,{
        params: params,
        headers: headers
      })
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err)
      })
    })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}){
    return new Promise((resolve, reject) => {
       axios.post(url, data)
       .then(response => {
         resolve(response.data);
       }, err => {
         reject(err)
       })
    })
}

/**
 * 封装二进制流POST请求（用于文件下载）
 * @param url 
 * @param data 
 * @returns {Promise<Blob>}
 */
export function postBlob(url, data = {}) {
  return new Promise((resolve, reject) => {
      axios.post(url, data, {
          responseType: 'blob' // 关键配置：声明接收二进制流[1,7](@ref)
      })
      .then(response => {
          resolve(response.data);
      })
      .catch(err => {
          reject(err);
      });
  });
}




